package com.huarui.employee.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.ewaf.framework.struts2.util.DateFormatUtil;
import org.ewaf.framework.util.MD5Digester;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.huarui.company.model.Company;
import com.huarui.company.util.JoinStringUtil;
import com.huarui.department.dao.IDepartmentDao;
import com.huarui.department.model.Department;
import com.huarui.employee.dao.IAddingEmployeeDao;
import com.huarui.employee.dao.IHireHistoryDao;
import com.huarui.employee.dao.impl.EmployeeDaoImpl;
import com.huarui.employee.model.AddingEmployee;
import com.huarui.employee.model.Employee;
import com.huarui.employee.model.EmployeeListModel;
import com.huarui.employee.model.HireHistory;
import com.huarui.user.dao.IUserDao;
import com.huarui.user.model.User;
import com.huarui.util.PinyinToolkit;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class EmployeeService extends BaseService {

	private IUserDao userDao;
	private IHireHistoryDao hireHistoryDao;
	private IDepartmentDao departmentDao;
	private IAddingEmployeeDao addingEmployeeDao;
	

	public void setAddingEmployeeDao(IAddingEmployeeDao addingEmployeeDao) {
		this.addingEmployeeDao = addingEmployeeDao;
	}

	public void setDepartmentDao(IDepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public void setUserDao(IUserDao userDao) {
		
		this.userDao = userDao;
	}

	public void setHireHistoryDao(IHireHistoryDao hireHistoryDao) {
		this.hireHistoryDao = hireHistoryDao;
	}

	private EmployeeDaoImpl getDao() {
		return (EmployeeDaoImpl) dao;
	}

	
	
	
	/*
	 * 将用户添加为员工
	 * 
	 * public void addStaff(final Integer userId, final int companyId) {
	 * transactionTemplate.execute(new TransactionCallback() { public Object
	 * doInTransaction(TransactionStatus status) {
	 * getDao().createStaff(userId,companyId); return null; } }); }
	 */

	/**
	 * 增加员工
	 */
	public void addEmployee(final AddingEmployee addingEmployee) {
		transactionTemplate.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				   
				   User user=null;
				
				   Integer companyId =addingEmployee.getCompanyId();
	
				   if(addingEmployee.getAddeeId()!=null){
				
					   user = (User)userDao.getById(addingEmployee.getAddeeId());
					   user.setCompanyId(companyId);
					   userDao.update(user);
								   
				   }else{
					   
					   user = new User();
					   user.setName(addingEmployee.getName());
					   user.setPassword(MD5Digester.digest(addingEmployee.getPassword()));
					   user.setStatus(User.STATUS_ACTIVED);
  				       user.setEmail(addingEmployee.getAddeeEmail());		   	
			           user.setCompanyId(companyId);
					   userDao.create(user);
				   }

				
				// 通过用户和公司找出唯一的员工，因为员工可能在很多公司工作过,每个公司都保存着员工记录
				Employee employee = getDao().getEmployeeByUserId(user.getId(),companyId,1);
				if (employee == null) {
					employee = new Employee();
					Department department= departmentDao.getByisDefault(companyId);
					if(addingEmployee.getDepartmentId()!=null&&addingEmployee.getDepartmentId()!=0){
						
						employee.setDepartmentId(addingEmployee.getDepartmentId());
					}else{
						
						employee.setDepartmentId(department.getId());
					}
					if(StringUtils.isNotBlank(addingEmployee.getCode())){
						
						employee.setCode(addingEmployee.getCode());
					}else{
						
						employee.setCode(JoinStringUtil.getCode());
					}
                    if(addingEmployee.getGmtHire()!=null){
                    	
                    	employee.setGmtHire(addingEmployee.getGmtHire());
                    	
                    }else{
                    	
                    	employee.setGmtHire(new Date());
                    }
    
                    	
                    employee.setName(addingEmployee.getName());
                    employee.setMemo(addingEmployee.getMemo());       
                    employee.setUserId(user.getId());
                    employee.setCompanyId(companyId);
					employee.setIncumbent(true);
					employee.setIsDelete(0);
					if(StringUtils.isNotBlank(employee
							.getName())){
					employee.setPyCode(PinyinToolkit.cn2FirstSpell(employee
							.getName()));
					}
					
					getDao().create(employee);
				} else {
					if(addingEmployee.getDepartmentId()!=null&&addingEmployee.getDepartmentId()!=0){
						
						employee.setDepartmentId(addingEmployee.getDepartmentId());
					}
                    if(StringUtils.isNotBlank(addingEmployee.getCode())){
						
						employee.setCode(addingEmployee.getCode());
					}
                    if(addingEmployee.getGmtHire()!=null){
                    	
                    	employee.setGmtHire(addingEmployee.getGmtHire());
                    	
                    }else{
                    	
                    	employee.setGmtHire(new Date());
                    }
                    employee.setName(addingEmployee.getName());
                    employee.setMemo(addingEmployee.getMemo());
					employee.setIncumbent(true);				
					employee.setIsDelete(0);
					getDao().update(employee);

				}

			    HireHistory hireHistory = new HireHistory();
				hireHistory.setUserId(user.getId());
				hireHistory.setCompanyId(companyId);
				hireHistory.setGmtCreate(employee.getGmtHire());
				hireHistory.setType(0);
				hireHistoryDao.create(hireHistory);
				
				addingEmployee.setAddeeEmployeeId(employee.getId());
				addingEmployee.setAddeeId(user.getId());
				addingEmployee.setActivateCode(null);
				addingEmployeeDao.update(addingEmployee);
				
				return status;
			}
		});
	}
	
	
	/**
	 * 删除员工
	 */
	public void deleteEmployee(final Employee employee,final Company company,final String evaluation) {
		transactionTemplate.execute(new TransactionCallback() {
			public Object doInTransaction(TransactionStatus status) {
			
				employee.setIncumbent(false);

				employee.setIsDelete(1);

				// 通过用户的id和员工的入职时间找到相对应的入职记录

				User user = (User) userDao.getById(employee.getUserId());

				user.setCompanyId(0);

				getDao().update(employee);

				HireHistory hireHistory = new HireHistory();

				hireHistory.setEvaluation(evaluation);

				hireHistory.setType(1);

				hireHistory.setUserId(user.getId());

				hireHistory.setCompanyId(company.getId());

				hireHistoryDao.create(hireHistory);

				userDao.update(user);
					
				return status;
			}
		});
	}

	public Employee getEmployeeByUserId(Integer userId, Integer companyId,Integer isDelete) {

		return getDao().getEmployeeByUserId(userId, companyId,isDelete);
	}

	/**
	 * 获得所有员工
	 */
	@SuppressWarnings("unchecked")
	public ListModel<Employee> getEmployeeByCompanyId(Integer companyId,EmployeeListModel lm) {
		Map map = new HashMap<String, String>();
		map.put("companyId", companyId);
		map.put("isDelete", lm.getIsDelete());
		map.put("orderBy", lm.getOrderBy());
		map.put("start", lm.getStart());
		map.put("pageSize", lm.getPageSize());
		map.put("desc", lm.isDesc());
		lm.setTotal(this.getDao().countByConditions(map));
		List<Employee> employeeList = getDao().getEmployeeByCompanyId(map);
 
		lm.setResult(employeeList);

		return lm;
	}

	public Employee getByCode(String code) {

		return getDao().getByCode(code);

	}

	public Employee getjoindictionary(Integer id, String varGroup) {

		return getDao().getJoinDictionary(id, varGroup);

	}

	public Map<String, Object> modifyEmployee(final Employee employee) {

		 final Map<String, Object> resultMap = new HashMap<String, Object>();

			transactionTemplate.execute(new TransactionCallback() {			
				@Override
				public Object doInTransaction(TransactionStatus status) {
					
					try {
						
						Employee oldEmployee = getDao().getEmployeeForUpdate(employee.getId());
						//System.out.println(DateFormatUtil.dateSecond(employee.getGmtModify()));
				        //System.out.println(DateFormatUtil.dateSecond(oldEmployee.getGmtModify()));
						if(!DateFormatUtil.dateSecond(employee.getGmtModify()).equals(DateFormatUtil.dateSecond(oldEmployee.getGmtModify()))){
							resultMap.put("already_be_modify", "该员工信息已被修改,请在刷新页面后再进行修改");
							
							return resultMap;
							
						}
						
						
						BeanUtils.copyProperties(oldEmployee, employee);					

						oldEmployee.setPyCode(PinyinToolkit.cn2FirstSpell(oldEmployee.getName()));
						getDao().update(oldEmployee);
					} catch (Exception e) {
						
						e.printStackTrace();
					}

	
					return null;
				}
		
			});
			
			return resultMap;
	}
	
	public String getNameByIdAndCompanyId(Integer id, Integer companyId) {
		return getDao().getNameByIdAndCompanyId(id, companyId);
	}

	
	public  Employee getEmployeeByCodeAndCompanyId(Map map){
		
		
		return getDao().getEmployeeByCodeAndCompanyId(map);
		
	}
}
